package com.itheima.health.service.impl;

import com.itheima.health.dao.MemberDao;
import com.itheima.health.pojo.Member;
import com.itheima.health.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberDao memberDao;

    @Transactional
    @Override
    public Member createOrUpdate(Member member) {

        Member pojo = memberDao.selectByPhoneNumber(member.getPhoneNumber());
        //根据手机号查询会员是否存在
        if(null != pojo) {
            //会员已存在，则更新
            member.setId(pojo.getId());
            memberDao.updateByIdSelective(member);
        }else {
            //调用DAO插入数据
            member.setRegTime(new Date());
            memberDao.insert(member);
        }
        return memberDao.selectById(member.getId());
    }

    //需要查询过去12个月，每个月月底的会员数量
    @Override
    public Map<String,Object> selectMemberCount() {

        Calendar calendar = Calendar.getInstance();
        //用于返回数据
        Map<String,Object> map = new HashMap<>();
        //构建months
        String[] months =new String[12];
        //构建memberCount
        int[] memberCount=new int[12];

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM");

        for(int i=11;i>=0;i--){
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH);
            int count = memberDao.selectCountByMonth(year,month);
            //把日期转换成前端需要的格式字符串
            months[i]=sdf.format(calendar.getTime());
            memberCount[i]=count;
            calendar.add(Calendar.MONTH,-1);
        }
        map.put("months",months);
        map.put("memberCount",memberCount);

        return map;
    }

    @Override
    public Member selectByPhoneNumber(String telephone) {
        return memberDao.selectByPhoneNumber(telephone);
    }

    @Override
    public void insert(Member member) {
        memberDao.insert(member);
    }

    @Override
    public Member findById(Integer id) {
       return memberDao.selectById(id);
    }
}

